import React, { useState, useEffect } from 'react';
import { Card, Descriptions, Button, Spin, message, Tag } from 'antd';
import { ArrowLeftOutlined, RedoOutlined } from '@ant-design/icons';
import { history, useParams, useModel } from '@umijs/max';
import { getBorrowingDetail, renewBorrowing } from '@/services/BorrowingAPI';
import type { BorrowingItem } from '@/types/borrowing';

const BorrowingDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [borrowing, setBorrowing] = useState<BorrowingItem | null>(null);
  const [loading, setLoading] = useState(false);

  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser;

  // 获取借阅记录详情
  const fetchBorrowingDetail = async () => {
    if (!id) return;

    setLoading(true);
    try {
      const res = await getBorrowingDetail(Number(id));
      setBorrowing(res.data);
    } catch (error) {
      message.error('获取借阅记录详情失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchBorrowingDetail();
  }, [id]);

  // 续借
  const handleRenew = async () => {
    if (!id) return;

    try {
      await renewBorrowing(Number(id));
      message.success('续借成功');
      fetchBorrowingDetail(); // 刷新详情
    } catch (error) {
      message.error('续借失败');
    }
  };

  // 状态标签
  const renderStatusTag = (status: string) => {
    const statusMap = {
      borrowed: { color: 'blue', text: '借阅中' },
      returned: { color: 'green', text: '已归还' },
      overdue: { color: 'red', text: '已逾期' },
    };
    const statusInfo = statusMap[status as keyof typeof statusMap] || { color: 'default', text: status };
    return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
  };

  if (loading) {
    return <div style={{ padding: 24, textAlign: 'center' }}><Spin size="large" /></div>;
  }

  if (!borrowing) {
    return <div>借阅记录不存在</div>;
  }

  // 检查是否有续借权限
  const canRenew = borrowing.status === 'borrowed' || borrowing.status === 'overdue';

  return (
    <div>
      <Card style={{ marginBottom: 16 }}>
        <Button 
          icon={<ArrowLeftOutlined />} 
          onClick={() => history.push('/borrowing/list')}
          style={{ marginRight: 8 }}
        >
          返回列表
        </Button>
        {canRenew && (
          <Button 
            type="primary" 
            icon={<RedoOutlined />} 
            onClick={handleRenew}
          >
            续借
          </Button>
        )}
      </Card>

      <Card title="借阅详情">
        <Descriptions bordered column={2}>
          <Descriptions.Item label="用户">{borrowing.user?.username || '-'}</Descriptions.Item>
          <Descriptions.Item label="图书">{borrowing.book?.title || '-'}</Descriptions.Item>
          <Descriptions.Item label="作者">{borrowing.book?.author || '-'}</Descriptions.Item>
          <Descriptions.Item label="借阅日期">{borrowing.borrow_date}</Descriptions.Item>
          <Descriptions.Item label="应还日期">{borrowing.due_date}</Descriptions.Item>
          <Descriptions.Item label="实际归还日期">
            {borrowing.return_date || '未归还'}
          </Descriptions.Item>
          <Descriptions.Item label="状态">
            {renderStatusTag(borrowing.status)}
          </Descriptions.Item>
          <Descriptions.Item label="创建时间">{borrowing.created_at}</Descriptions.Item>
          <Descriptions.Item label="更新时间">{borrowing.updated_at}</Descriptions.Item>
          <Descriptions.Item label="备注" span={2}>
            {borrowing.notes || '无'}
          </Descriptions.Item>
        </Descriptions>
      </Card>
    </div>
  );
};

export default BorrowingDetail;